<template>
    <a-modal
            v-model="modal1"
            title="修改PIN码"
            :width="550"
            :maskClosable="false"
            :destroyOnClose="true"
            @ok="saveEditPinCode"
            @cancel="cancelEditPinCode"
            okText="确定"
            cancelText="取消"
    >
        <div>
            <a-form  :form="form" @keydown.native.enter.prevent="saveEditPinCode">
                <a-form-item label="安全UKey" v-bind="formStyle">
                    <a-input v-model="updPinCodeform.serialNum"  read-only/>
                    <div class="ivu-form-item-error-tip">{{devMsg}}</div>
                </a-form-item>
                <a-form-item v-for="(k, index) in formPwd" :key="index" v-bind="formStyle" :label="k.label">
                    <a-input
                            v-model="k.value"
                            :type="k.pwdType"
                            style="position: relative;"
                            :id="'refocus' + index"
                            @change="valideNewPassword(k.index, k.value, k.label)"
                            onpaste="return false"
                            oncopy="return false"
                            oncut="return false"
                    >
                        <a-icon slot="suffix" :type="k.eyeStatusName" @click="showOldPass(k)" style="  color: rgba(0,0,0,.65)" />
                    </a-input>
                    <div style="color:red; position: absolute; left: 0; top: 18px; font-size: 11px">{{ k.errMsg }}</div>
                </a-form-item>
                <div>
                    <span v-if ='showLoadUrl' style="font-size: 12px;color: #06f130;cursor: pointer;float: right;margin-top: -10px;margin-right: 13px;"
                          @click="downLoadUkeyDevice()" >下载UKey实体鉴别客户端</span>
                    <iframe id="ifile" title="下载UKey实体鉴别客户端" style="display: none"></iframe>
                </div>
            </a-form>
            <div style="margin-top: 20px">
                <span style="color: red">验证规则:</span>
                <br/>
                <span style="color: red">1、密码不能为空</span>
                <br/>
                <span style="color: red">2、两次输入的新密码要相同</span>
                <br/>
                <span style="color: red">3、密码应满足长度6-16字符，且只能是字母和数字</span>
            </div>
        </div>
    </a-modal>
</template>

<script>
  import util from '@/libs/util.js';
  import * as State from "@/libs/baseStateConts";
  const Base64 = require('js-base64').Base64;
  export default {
      name: 'editPin',
      data () {
          const valideRePassword = (rule, value, callback) => {
              value = util.empty(value);
              if (!value || value.trim().length === 0) {
                  callback(new Error('必填项'));
              }else if (value !== this.updPinCodeform.newPass) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
          };
          const pwdregT= /^[a-zA-Z0-9_]+$/;
          const valideNewPassword = (rule, value, callback) => {
            if (!value || value.trim().length === 0) {
              callback(new Error('必填项'));
            }else if(value.length > 16 || value.length < 6){
              callback(new Error('请输入6-16位有效密码！'));
            }else if (!pwdregT.test(value)) {
              callback(new Error('请输入包含大小写字母或数字的有效密码！'));
            } else if (value === '111111' || value === 'QaSky20191818') {
              callback(new Error('禁止输入初始化密码！'));
            }else {
              callback();
            }
          };
          const validePassword = (rule, value, callback) => {
            value = util.empty(value);
            if (!value || value.trim().length === 0) {
              callback(new Error('请输入原密码'));
            }else {
              callback();
            }
          };

          return {
              scanUKeyTimer: -1,
              showLoadUrl:false,
              modal1: false,
              pwdType: 'password', // 密码框显示密码的控制
              eyeStatusName: 'eye-disabled', // 密码框显示密码的图标展示控制
              updPinCodeform: {
                  serialNum:'',
                  oldPass: '',
                  newPass: '',
                  rePass: ''
              },
              form: this.$form.createForm(this),
              msg: '',
              devMsg:'',
              save_loading: false,
              savePassLoading: false,
              oldPassError: '',
              checkIdentifyCodeLoading: false,
              formStyle: {
                  labelCol: { span: 6 },
                  wrapperCol: { span: 17 }
              },
              formPwd: [
                  { index: 0, label: '原密码', name: 'oldPassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' },
                  { index: 1, label: '新密码', name: 'newPassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' },
                  { index: 2, label: '确认新密码', name: 'rePassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' }
              ],
          }
      },
      methods: {

          /**
           * Function    : startScanTimer
           * Description : 开启扫描UKey设备定时器
           * a-input       : None
           * Return      : None
           */
          startScanTimer() {
              let _this = this;
              if (_this.scanUKeyTimer !== -1) {
                  return;
              }

              //开启扫描外接密钥存储设备定时器
              _this.scanUKeyTimer = setInterval(function() {
                  _this.updDevSerialNum ();
              }, 1000 * 1);
          },

          /**
           * Function    : updDevSerialNum
           * Description : 更新UKey设备序列号
           * a-input       : None
           * Return      : None
           */
          updDevSerialNum () {
              let _this = this;
              _this.$axios.get(this.$uurl+'/ukeyauth/getDeviceSerialNum').then(response => {
                  let respData = response.data;
                  _this.showLoadUrl = false;
                  if (respData.code !== 0)  {
                      _this.updPinCodeform.serialNum = '';
                      _this.devMsg = '请插入安全UKey';
                      return ;
                  }
                  if (_this.updPinCodeform.serialNum !== respData.data)  {
                      _this.updPinCodeform.serialNum = respData.data;
                  }
                  _this.devMsg = '';
              }).catch( e => {
                  _this.clearScanTimer();
                  _this.showLoadUrl = true;
              });
          },

        /**
         * Function    : clearScanTimer
         * Description : 关闭扫描UKey设备定时器
         * a-input       : None
         * Return      : None
         */
        clearScanTimer () {
          let _this = this;
          //关闭定时器、并且提示用户出错信息
          if (_this.scanUKeyTimer === -1) {
            return;
          }
          clearInterval(_this.scanUKeyTimer);
          _this.scanUKeyTimer = -1;
        },

          /**
           * Function    : downLoadUkeyDevice
           * Description : 下载U盾认证登录驱动
           * a-input       : None
           * Return      : None
           */
          downLoadUkeyDevice() {
            document.getElementById ('ifile').src = State.downloadUKeyAuthTool;
          },


          /**
           * Function    : valideNewPassword
           * Description : 验证新密码的规则一致
           * Input       : none
           * Return      : none
           */
          valideNewPassword(index, value, label) {
              let msg = ''
              if (typeof value === 'undefined') {
                  return
              }
              value = value.replace(/\s/g, '')
              const res2 = /^[a-zA-Z0-9_]+$/;
              if (value.length > 16) {
                  value = value.substring(0, 16)
              }
              this.formPwd[index].value = value
              if (index !== 2) {
                  if (value.trim().length === 0) {
                      msg = '请输入包含大小写字母或数字的有效密码！'
                  } else if (!res2.test(value)) {
                      msg = '请输入包含大小写字母或数字的有效密码！'
                  } else if (value.length > 16 || value.length < 6) {
                      msg = '请输入6-16位有效密码'
                  } else {
                       if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value === this.formPwd[2].value) {
                          this.formPwd[2].errMsg = ''
                          if ((this.formPwd[1].value === 'QaSky20191818'|| this.formPwd[1].value === '111111') && index === 1) {
                              msg = '禁止输入初始化密码'
                          }
                      } else if ((this.formPwd[1].value === 'QaSky20191818'|| this.formPwd[1].value === '111111') && index === 1) {
                          msg = '禁止输入初始化密码'
                      } else if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value !== this.formPwd[2].value) {
                          this.formPwd[2].errMsg = '两次输入密码不一致'
                      }
                  }
                  this.formPwd[index].errMsg = msg
              } else {
                  if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value !== this.formPwd[2].value) {
                      this.formPwd[2].errMsg = '两次输入密码不一致'
                  } else if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value === this.formPwd[2].value) {
                      this.formPwd[2].errMsg = ''
                  }
              }
          },
          // 是否明码展示所填密码
          showOldPass(k) {
              if (k.pwdType === 'password') {
                  k.pwdType = 'text'
                  k.eyeStatusName = 'eye'
              } else {
                  k.pwdType = 'password'
                  k.eyeStatusName = 'eye-invisible'
              }
          },

          /**
           * Function    : cancelEditPinCode
           * Description : 取消修改PIN码
           * a-input       : editForm
           * Return      : None
           */
           cancelEditPinCode () {
              let _this = this;
              let isDefaultPinCode = sessionStorage.getItem('isDefaultPinCode');
              if (isDefaultPinCode === 'true') {
                  _this.$store.dispatch("logoutAct");
                  _this.$get(this.$uurl+'/ukeyauth/logoutDev');

                  // 退出登录
                  _this.$store.commit('logout',this);
                  _this.$store.commit('clearOpenedSubmenu');
                  sessionStorage.clear();

                  //延时2s返回登录页
                  setTimeout(function () {
                      _this.$router.push({
                          name: 'login'
                      });
                  }, 1 * 1000);

              }
              setTimeout(function() {
                  _this.formPwd.forEach(item => {
                      item.value = ''
                      item.errMsg = ''
                      item.pwdType = 'password'
                      item.eyeStatusName = 'eye-invisible'
                  })
              }, 100)
              _this.clearScanTimer ();
              _this.modal1 = false;
           },

          /**
           * Function    : saveEditPinCode
           * Description : 保存修改PIN码
           * a-input       : editForm
           * Return      : None
           */
          saveEditPinCode (e) {
              let _this =this
              e.preventDefault()
              let isNull = false
              let isRight = true
              this.formPwd.forEach(item => {
                  if (item.value === '' || item.value === undefined) {
                      isNull = true
                      item.errMsg = item.label + '不能为空'
                  }
                  if (item.errMsg !== '') {
                      isRight = false
                  }
              })
              this.form.validateFields((err, value) => {
                  if (isNull || !isRight) {
                      return
                  }
                  if (!err) {
                      _this.savePassLoading = true;
                      _this.msg = '';
                      _this.devMsg = '';
                      let params = {
                          'originPinCode': util.empty(Base64.encode(this.formPwd[0].value)),
                          'pinCode': util.empty(Base64.encode(this.formPwd[1].value))
                      };
                      _this.$axios.get(this.$uurl+'/ukeyauth/updDevPinCode', {params:params}).then(response => {
                          response = response.data;
                          if (response.code === 0) {
                              _this.clearScanTimer ();
                              _this.modal1 = false;

                              _this.$message.success('修改成功，请重新登录')

                              _this.$axios.get(this.$uurl+'/ukeyauth/logoutDev');
                              // _this.$store.dispatch("logoutAct");
                              sessionStorage.clear();

                              //延时2s返回登录页
                              setTimeout(function () {
                                  _this.$router.push({
                                      name: 'login'
                                  });
                              }, 1 * 1000);
                              window.location.reload();
                          } else {
                              _this.$message.error(response.message);
                          }
                      }).catch( e => {
                      });
                  }
              })
          },

          showModal () {
              this.startScanTimer();
              this.modal1 = true
          }
      }
  }
</script>
<style lang="less" scoped>

</style>
